package com.example.service

import com.example.data.dbQuery
import com.example.data.entity.CollectEntity
import com.example.data.entity.HistoryEntity
import com.example.data.model.Collect
import com.example.tSimpleDateFormat
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq

class CollectService {
    suspend fun get(username: String, page: Int, pageSize: Int): List<Collect> {
        return dbQuery {
            CollectEntity.select { CollectEntity.username eq username }.orderBy(CollectEntity.date to SortOrder.DESC)
                .limit(pageSize, (pageSize * (page - 1)).toLong()).map {
                    Collect(
                        it[CollectEntity.id],
                        it[CollectEntity.asmrId],
                        tSimpleDateFormat.format(it[CollectEntity.date]),
                        it[CollectEntity.img],
                        it[CollectEntity.title],
                        it[CollectEntity.username]
                    )
                }
        }
    }

    suspend fun add(collect: Collect) = dbQuery {
        CollectEntity.insert {
            it[asmrId] = collect.asmrId
            it[date] = System.currentTimeMillis()
            if (collect.img != null) it[img] = collect.img
            if (collect.title != null) it[title] = collect.title
            it[username] = collect.username!!
        }.insertedCount > 0
    }

    suspend fun delete(id: Int,username:String) = dbQuery {
        CollectEntity.deleteWhere {
            (CollectEntity.asmrId eq id) and (CollectEntity.username eq username)
        } > 0
    }

    suspend fun clear(u: String) = dbQuery {
        CollectEntity.deleteWhere {
            username eq u
        } > 0
    }

    suspend fun isCollect(asmrId: Int, username: String): Boolean = dbQuery {
        CollectEntity.select {
            (CollectEntity.username eq username) and (CollectEntity.asmrId eq asmrId)
        }.count() > 0
    }
}